package com.gobo.jinghuimall.product.service.impl;

import com.gobo.jinghuimall.product.entity.SkuImagesEntity;
import com.gobo.jinghuimall.product.entity.SpuInfoDescEntity;
import com.gobo.jinghuimall.product.entity.SpuInfoEntity;
import com.gobo.jinghuimall.product.service.*;
import com.gobo.jinghuimall.product.vo.SkuItemSaleAttrVo;
import com.gobo.jinghuimall.product.vo.SkuItemVo;
import com.gobo.jinghuimall.product.vo.SpuItemAttrGroupVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gobo.common.utils.PageUtils;
import com.gobo.common.utils.Query;

import com.gobo.jinghuimall.product.dao.SkuInfoDao;
import com.gobo.jinghuimall.product.entity.SkuInfoEntity;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }


    /**
     * key: 1
     * catelogId: 225
     * brandId: 4
     * min: 0
     * max: 0
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String min = (String) params.get("min");
        BigDecimal minBigDecimal =null;
        try{
            minBigDecimal = new BigDecimal(min);
        }catch (Exception e){
            log.error("价格传入异常！");
        }
        if (!StringUtils.isEmpty(min)){
            queryWrapper.ge("price",minBigDecimal);
        }
        String max = (String) params.get("max");
        BigDecimal maxBigDecimal =null;
        try{
            maxBigDecimal = new BigDecimal(max);
        }catch (Exception e){
            log.error("价格传入异常！");
        }
        if (!StringUtils.isEmpty(max) && maxBigDecimal.compareTo(new BigDecimal("0"))==1){
            queryWrapper.le("price",maxBigDecimal);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and(obj->{
                obj.eq("sku_id",key).or().like("sku_name",key);
            });
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);

    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> spu_id = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return spu_id;
    }

    /**
     * 获取详情页需要的信息
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVo itemInfo(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            //1、sku基本信息的获取  pms_sku_info
            SkuInfoEntity info = this.getById(skuId);
            skuItemVo.setSkuInfoEntity(info);
            return info;
        }, threadPoolExecutor);


        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //3、获取spu的销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setSpuSaleAttrs(saleAttrVos);
        }, threadPoolExecutor);


        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync((res) -> {
            //4、获取spu的介绍    pms_spu_info_desc
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setSpuDesc(spuInfoDescEntity);
        }, threadPoolExecutor);


        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync((res) -> {
            //5、获取spu的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setSpuAttrGroupVos(attrGroupVos);
        }, threadPoolExecutor);


        // Long spuId = info.getSpuId();
        // Long catalogId = info.getCatalogId();

        //2、sku的图片信息    pms_sku_images
        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            List<SkuImagesEntity> imagesEntities = skuImagesService.getBySkuId(skuId);
            skuItemVo.setSkuImages(imagesEntities);
        }, threadPoolExecutor);
        skuItemVo.setHasStock(true);
        //等到所有任务都完成
        try {
            CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imageFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.error("多线程异步编排线程中断异常:"+e.getStackTrace());
        } catch (ExecutionException e) {
            log.error("多线程异步编排线程执行异常:"+e.getStackTrace());
        }
        return skuItemVo;
    }

    @Override
    public SkuInfoEntity getSkuInfo(Long skuId) {
        return this.getById(skuId);
    }

}